from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QHeaderView, QAbstractItemView, QTableWidgetItem, QMessageBox

from entity import currentuser
from opsql import studentOp


class Com():
    def __init__(self):
        self.ui = QUiLoader().load('view/电脑.ui')
        self.ui.searchBtn.clicked.connect(self.search)
        self.ui.startBtn.clicked.connect(self.start)
        self.ui.endBtn.clicked.connect(self.end)
        self.inittable()

    def inittable(self):
        result = studentOp.searchallcomputer()
        row = 0
        if result:
            row = len(result)
        self.ui.tableWidget.setRowCount(row)
        self.ui.tableWidget.setColumnCount(5)
        self.ui.tableWidget.setHorizontalHeaderLabels(['电脑id', '电脑类别', '机房', '机房类型', '价格（元/小时）'])
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableWidget.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.ui.tableWidget.verticalHeader().setVisible(False)
        self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)

        for i in range(row):
            for j in range(5):
                data = QTableWidgetItem(str(result[i][j]))
                self.ui.tableWidget.setItem(i, j, data)

    def search(self):
        ct=self.ui.ctIn.text()
        rt=self.ui.rtIn.text()
        result=studentOp.searchcomputer(ct,rt)
        row = 0
        if result:
            row = len(result)
        self.ui.tableWidget.setRowCount(row)
        self.ui.tableWidget.setColumnCount(5)
        self.ui.tableWidget.setHorizontalHeaderLabels(['电脑id', '电脑类别', '机房', '机房类型', '价格（元/小时）'])
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableWidget.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.ui.tableWidget.verticalHeader().setVisible(False)
        self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)

        for i in range(row):
            for j in range(5):
                data = QTableWidgetItem(str(result[i][j]))
                self.ui.tableWidget.setItem(i, j, data)

    def start(self):
        row=self.ui.tableWidget.currentRow()
        sid=currentuser.current_userid
        cid=int(self.ui.tableWidget.item(row,0).text())
        flag=studentOp.ifstart(sid)
        if flag>0:
            QMessageBox.warning(self.ui,'提示','您已打开过一台电脑')
            return
        else:
            if studentOp.addorder(sid,cid):
                QMessageBox.information(self.ui,'提示','开机成功')
            else:
                QMessageBox.warning(self.ui,'提示','开机失败')
            self.inittable()

    def end(self):
        sid=currentuser.current_userid
        result=studentOp.endcomputer(sid)
        if result>0:
            QMessageBox.information(self.ui,'提示','电脑已归还')
        else:
            QMessageBox.warning(self.ui,'提示','您未开机')
        self.inittable()